Reading and Writing Files¶

🎨 Reading files¶

reading.py¶

sum_from_file.py¶

🎨 Writing files¶

writing.py¶

all_caps.py¶

👩🏻‍🎨 exciting.py¶

boring_file.txt¶

Write a program that can make boring_file.txt into something more exciting.

In [ ]:
%%bash
python for_class/exciting_solution.py for_class/boring_file.txt exciting_file.txt && cat exciting_file.txt && rm exciting_file.txt

What happens when you mix up the file you want to read with the file you want to write?¶

If you try to read a file that doesn't exist, you'll get a FileNotFound error.

If you try to write a file that doesn't exist, python will make it exist (this is typically exactly what we want).

If you try to read a file that exists, python opens the file and you can read it.

If you try to write a file that exists, python erases everything that used to be there and starts fresh.

😳

With great power comes great responsibility

Measure twice, cut once.

Always double check which file you are opening before you run your code.
Never write to the wrong file!
Always store a backup of important files you will touch with code!

👨🏼‍🎨 BYU Count¶

Write a program that takes an input file and output file as commandline arguments.

For each line in the input file, write a line in the output file that has the corresponding number of "B", "Y", or "U" characters found in the input line. Ignore casing.

Input

Your big book is ugly.
Yuba is beyond.

Output

6
5

NOTES

  • What does the main method look like?
    • Read lines, make new lines, write lines
  • What does the "make new lines" process look like?
    • 'BYU!' -> 3 -> '3\n'
  • What functions can I create for each step of that process?

Key Ideas¶

  • Reading files
  • Writing files
  • Thinking about the sequence of changes made to data